from django.db import models
from user.models import SysUser


class Role(models.Model):
    """
    角色信息表

    字段说明:
    - name: 角色名称
    - key:  角色标识（如 admin、manager、member）
    - status: 状态（0 正常，1 停用）
    - remark: 备注
    - create_time/update_time: 创建/更新时间
    """
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100, unique=True, verbose_name="角色名称", db_comment="角色名称")
    key = models.CharField(max_length=100, unique=True, verbose_name="角色标识", db_comment="角色标识")
    status = models.IntegerField(default=0, verbose_name="状态（0正常 1停用）", db_comment="状态（0正常 1停用）")
    remark = models.CharField(max_length=255, null=True, blank=True, verbose_name="备注", db_comment="备注")
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", db_comment="创建时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间", db_comment="更新时间")

    class Meta:
        db_table = 'sys_role'
        verbose_name = '角色管理'
        ordering = ['id']

    def __str__(self):
        return self.name


class UserRole(models.Model):
    """
    用户-角色关联表（中间表）
    """
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(SysUser, on_delete=models.CASCADE, related_name='user_roles', db_comment='用户')
    role = models.ForeignKey(Role, on_delete=models.CASCADE, related_name='role_users', db_comment='角色')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间", db_comment="创建时间")

    class Meta:
        db_table = 'sys_user_role'
        verbose_name = '用户角色关联'
        unique_together = ('user', 'role')

